import React from 'react';
import { Select } from 'antd';
import { GlobalOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';

const { Option } = Select;

const LanguageSwitcher: React.FC = () => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();

  const handleLanguageChange = (language: string) => {
    i18n.changeLanguage(language);
    
    // 更新 URL 中的语言参数
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const currentLang = pathSegments[0];
    
    // 如果当前路径已经包含语言代码，替换它
    if (['zh', 'th'].includes(currentLang)) {
      pathSegments[0] = language;
    } else {
      // 如果没有语言代码，添加到开头
      pathSegments.unshift(language);
    }
    
    const newPath = '/' + pathSegments.join('/');
    navigate(newPath + location.search + location.hash);
  };

  return (
    <Select
      value={i18n.language}
      onChange={handleLanguageChange}
      style={{ width: 120 }}
      suffixIcon={<GlobalOutlined />}
      size="small"
    >
      <Option value="zh">{t('language.chinese')}</Option>
      <Option value="th">{t('language.thai')}</Option>
    </Select>
  );
};

export default LanguageSwitcher;
